/**
 * 
 */
package io.dora.conf.spring;

import io.dora.conf.ProtocolConfig;
import io.dora.conf.ProviderConfig;
import io.dora.conf.RegistryConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

/**
 * Provider spring 配置Bean
 * 
 * @author zhaohongbo
 *
 */
public class ProviderBean<T> extends ProviderConfig<T> implements InitializingBean, DisposableBean, ApplicationContextAware, ApplicationListener, BeanNameAware, ConfigInitializingBean {
	
	private static final Logger LOG = LoggerFactory.getLogger(ProviderBean.class);
	
	private ApplicationContext applicationContext;

	@Override
	public void setBeanName(String name) {
		
	}

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public void destroy() throws Exception {
		
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		export();
	}
	
	@SuppressWarnings({"unchecked" })
	@Override
	public void export() {
		this.setRef((T) applicationContext.getBean(this.getRefBeanId()));
		this.initial();
		LOG.info("Ref bean id:[{}]", this.getRefBeanId());
		super.export();
	}

	@Override
	public void initial() {
		this.setRegistry(this.getBeanInstance(applicationContext, RegistryConfig.class).getRegistry());
		this.setProtocol(this.getBeanInstance(applicationContext, ProtocolConfig.class).getProtocol());
	}
	
}
